/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
import tal.drivechain.chain.AbortChainException;
import tal.drivechain.matchers.VarMatcher;
import tal.drivechain.plugin.Channel;
import tal.drivechain.plugin.Module;
import tal.drivechain.variable.types.ArrayType;
import tal.drivechain.variable.types.DataType;
import tal.drivechain.variable.SetProperty.Flag;
import tal.drivechain.variable.Variable;

/**
 *
 * @author Main
 */
public class FileIn extends Module {
    File file = null;
    VarMatcher readTrigger;
    Variable out;
    boolean textInput;
    
    @Override
    public void setupProperties() throws IllegalArgumentException, AbortChainException {
        setFilename(props.getProperty("filename"), null);
        setReadTrigger(props.getProperty("readTrigger"), null);
        setTextInput(props.getProperty("textInput"), null);
        setOutputName(props.getProperty("outputName"), null);
    }

    public void setFilename(Object value, Flag flag) {
        if (value==null)
            file = null;
        else file = (File)value;
    } public Object getFilename() { return file; }

    public void setReadTrigger(Object value, Flag flag) {
        readTrigger = (VarMatcher)value;
    } public Object getReadTrigger() { return readTrigger; }

    public void setOutputName(Object value, Flag flag) {
        String varName;
        if (value==null)
            varName = this.getName();
        else varName = (String)value;
        if (out==null)
            out = new Variable(varName, new ArrayType(DataType.VAR), new ArrayList<Object>(), true);
        else out.setName(varName);
    } public Object getOutputName() { return out.getName(); }

    public void setTextInput(Object value, Flag flag) {
        textInput = (Boolean)value;
    } public Object getTextInput() { return textInput; }

    @Override
    protected void msgReceived(Variable in, long timestamp, Channel channel) {
        if (file==null) {
            if (debugFlag && readTrigger.matches(in, channel, this))
                log("Received read trigger while filename is not set.", MSG.DEBUG);
            return;
        }
        if (readTrigger.matches(in, channel, this)) {
            try {
                if (debugFlag) log("Reading from '" + file + "'", MSG.INFO);
                readFile(file);
                this.sendToOutputs(out, timestamp);
            } catch (IOException ex) {
                log("While trying to read from file: '" + file + "': " + ex.getMessage(), MSG.WARNING);
            } 
        } 
    }

    private void readFile(File file) throws IOException {
        ((List<Object>)out.getInternalValue()).clear();        
        if (textInput) {
            BufferedReader input = null;
            StringBuilder contents = new StringBuilder();
            try {
                try {
                    input = new BufferedReader(new FileReader(file));
                } catch (FileNotFoundException ex) {
                    throw new IllegalArgumentException("File not found: " + file.getAbsolutePath());
                }
                String line = null;
                while ((line = input.readLine())!=null)
                    contents.append(line).append(System.getProperty("line.separator"));
            } catch (IOException ex){
                throw new IllegalArgumentException(ex.getMessage());
            } finally {
                try {
                    if (input!= null)
                        input.close();
                } catch (IOException ex) {
                    throw new IllegalArgumentException(ex.getMessage());
                }
            }
            String outString = contents.toString();
            ((List<Object>)out.getInternalValue()).add(outString);
        } else {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            try {
                List<Variable> variables = (List<Variable>)in.readObject();
                for (Variable var : variables) {
                    ((List<Object>)out.getInternalValue()).add(var.getValue(this));
                }
            } catch (ClassNotFoundException ce) {
                log("Invalid format in file '" + file + "'", MSG.WARNING);                
            } catch (ClassCastException ce) {
                log("Invalid format in file '" + file + "'", MSG.WARNING);
            }
        }
        
    }

    public void read(String... filenames) {
        if (filenames.length>0) {
            for (String s : filenames) {
                File tempFile = new File(s);
                try {
                    readFile(tempFile);
                    sendToOutputs(out, -1);
                } catch (Exception ex) {
                    log("While trying to read from file: '" + tempFile + "': " + ex, MSG.WARNING);
                }
            }
        } else log("Invalid read command. At least 1 parameter is required.", MSG.WARNING);
    }
}
